package org.ch02.job.test10;

import org.ch02.job.test08.SqlGenerate;
import org.ch02.job.test10.User;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.ch02.job.test10.BuildFull.buildFullSql;

/**
 * @author XCH
 * @date 2025 - 03 - 19
 */
public class DbUtil {
    // 定义数据库连接URL
    private static final String URL = "jdbc:mysql://localhost:3306/stu?serverTimezone=UTC&useSSL=false&characterEncoding=utf8";


    // 定义数据库驱动类
    private static final String driver = "com.mysql.cj.jdbc.Driver";

    // 定义数据库用户
    private static final String username = "root";

    // 定义数据库密码
    private static final String password = "root";
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("数据库驱动加载失败", e);
        }
    }

    public static Object select4Bean(Class<?> beanClass, Map<String,Object> cond) throws Exception {
        String sql = SqlGenerate.generateSelect(beanClass);
        StringBuilder sql1 = new StringBuilder();

        for (String key : cond.keySet()) {
            if (sql1.length() > 0) {
                sql1.append(" AND ");
            }
            sql1.append(key).append(" = ?");
        }

        if (sql1.length() > 0) {
            sql += " WHERE " + sql1.toString();
        }
        System.out.println(sql);

        return queryDatabase(sql, cond);
    }

    private static Object queryDatabase(String sql, Map<String, Object> cond) {
        try (Connection conn = DriverManager.getConnection(URL, username, password);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            System.out.println("原始 SQL 语句：" + sql);

            int index = 1;
            for (String key : cond.keySet()) {
                stmt.setObject(index++, cond.get(key));
            }

            // 输出带有实际参数的 SQL 语句
            String fullSql = buildFullSql(sql, cond);


            System.out.println("完整 SQL 语句：" + fullSql.toString());

            ResultSet resultSet = stmt.executeQuery();

            if (resultSet.next()) {
                Class<?> userClass = Class.forName("org.ch02.job.test10.User");
                Object user = userClass.getDeclaredConstructor().newInstance();
                Field[] fields = userClass.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    Object value = resultSet.getObject(fieldName);
                    field.set(user, value);
                }

                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
